<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DashScope I2V 视频生成</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2em;
            margin-bottom: 10px;
        }

        .content {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            height: 80px;
            resize: vertical;
        }

        /* 文件上传样式 */
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 12px;
            padding: 30px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #f8f9ff;
            margin-bottom: 15px;
        }

        .upload-area:hover {
            border-color: #5a67d8;
            background: #f0f4ff;
        }

        .upload-icon {
            font-size: 2em;
            margin-bottom: 10px;
        }

        .upload-hint {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        /* 图片预览 */
        .image-preview {
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            background: white;
            text-align: center;
        }

        .image-preview img {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            margin-bottom: 10px;
        }

        .preview-info {
            font-size: 0.9em;
            color: #666;
        }

        /* 按钮样式 */
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-small {
            background: #f8d7da;
            color: #721c24;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 12px;
            cursor: pointer;
            margin-left: 10px;
        }

        .btn-small:hover {
            background: #f5c6cb;
        }

        /* 结果显示 */
        .result-section {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            margin-top: 20px;
        }

        .result-section h3 {
            color: #333;
            margin-bottom: 15px;
        }

        .result-box {
            background: white;
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
        }

        .status {
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
        }

        .status.pending {
            background: #fff3cd;
            color: #856404;
        }

        .video-result {
            text-align: center;
            margin-top: 15px;
        }

        .video-result video {
            max-width: 100%;
            border-radius: 8px;
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }

        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎬 DashScope I2V 视频生成</h1>
            <p>上传图片，生成精彩视频</p>
        </div>

        <div class="content">
            <!-- 图片上传 -->
            <div class="form-group">
                <label>选择图片：</label>
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <div class="upload-icon">📁</div>
                    <p>点击选择图片文件</p>
                    <p class="upload-hint">支持 JPEG、PNG、BMP、WEBP，最大 10MB</p>
                </div>
                <input type="file" id="fileInput" accept="image/*" style="display: none;" onchange="handleFileSelect(event)">
                
                <!-- 图片预览 -->
                <div id="imagePreview" class="image-preview" style="display: none;">
                    <img id="previewImg" alt="预览图片">
                    <div class="preview-info">
                        <span id="fileInfo"></span>
                        <button type="button" class="btn-small" onclick="clearImage()">清除</button>
                    </div>
                </div>
            </div>

            <!-- 提示词 -->
            <div class="form-group">
                <label for="prompt">提示词：</label>
                <textarea id="prompt" placeholder="描述您希望生成的视频内容，如：一只猫在草地上奔跑"></textarea>
            </div>

            <!-- 参数设置 -->
            <div class="form-group">
                <label for="resolution">分辨率：</label>
                <select id="resolution">
                    <option value="1080P">1080P (推荐)</option>
                    <option value="480P">480P</option>
                </select>
            </div>

            <div class="form-group">
                <div class="checkbox-group">
                    <input type="checkbox" id="promptExtend" checked>
                    <label for="promptExtend">开启智能提示词扩展</label>
                </div>
            </div>

            <!-- 操作按钮 -->
            <button class="btn" id="generateBtn" onclick="generateAndWait()">
                🚀 生成视频
            </button>

            <!-- 结果展示 -->
            <div class="result-section">
                <h3>📊 执行结果</h3>
                <div id="status" class="status" style="display: none;"></div>
                <div id="result" class="result-box">等待上传图片...</div>
                <div id="videoResult" class="video-result" style="display: none;"></div>
            </div>
        </div>
    </div>

    <script>
        const BASE_URL = 'http://localhost:8081';
        let currentImageBase64 = '';

        // 文件选择处理
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                uploadImage(file);
            }
        }

        // 上传图片
        async function uploadImage(file) {
            showStatus('正在上传图片...', 'pending');
            
            // 客户端验证
            if (!file.type.startsWith('image/')) {
                showStatus('请选择图片文件', 'error');
                return;
            }
            
            if (file.size > 10 * 1024 * 1024) {
                showStatus('文件大小不能超过10MB', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch(`${BASE_URL}/api/upload/image`, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentImageBase64 = data.base64;
                    showImagePreview(data.base64, data.filename, data.size);
                    showStatus('图片上传成功！可以生成视频了', 'success');
                    showResult(data);
                } else {
                    showStatus('图片上传失败: ' + data.message, 'error');
                    showResult(data);
                }
                
            } catch (error) {
                showStatus('上传失败: ' + error.message, 'error');
                showResult({error: error.message});
            }
        }

        // 显示图片预览
        function showImagePreview(base64Url, filename, size) {
            const previewDiv = document.getElementById('imagePreview');
            const previewImg = document.getElementById('previewImg');
            const fileInfo = document.getElementById('fileInfo');
            
            previewImg.src = base64Url;
            fileInfo.textContent = `${filename} (${formatFileSize(size)})`;
            previewDiv.style.display = 'block';
        }

        // 清除图片
        function clearImage() {
            currentImageBase64 = '';
            document.getElementById('fileInput').value = '';
            document.getElementById('imagePreview').style.display = 'none';
            showStatus('图片已清除', 'success');
            showResult('等待上传图片...');
        }

        // 生成视频（直接等待完成）
        async function generateAndWait() {
            if (!currentImageBase64) {
                showStatus('请先上传图片', 'error');
                return;
            }

            const prompt = document.getElementById('prompt').value;
            const resolution = document.getElementById('resolution').value;
            const promptExtend = document.getElementById('promptExtend').checked;

            const requestData = {
                model: 'wan2.2-i2v-plus',
                input: {
                    img_url: currentImageBase64,
                    prompt: prompt
                },
                parameters: {
                    resolution: resolution,
                    prompt_extend: promptExtend
                }
            };

            setLoading(true);
            showStatus('正在生成视频，预计需要1-2分钟...', 'pending');

            try {
                const response = await fetch(`${BASE_URL}/api/video/generateAndWait`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();
                
                if (data.success && data.videoUrl) {
                    showStatus('视频生成成功！', 'success');
                    showVideoResult(data.videoUrl);
                } else {
                    showStatus('视频生成失败: ' + data.message, 'error');
                }
                
                showResult(data);
            } catch (error) {
                showStatus('请求失败: ' + error.message, 'error');
                showResult({error: error.message});
            } finally {
                setLoading(false);
            }
        }

        // 显示状态
        function showStatus(message, type = 'pending') {
            const statusEl = document.getElementById('status');
            statusEl.textContent = message;
            statusEl.className = 'status ' + type;
            statusEl.style.display = 'block';
        }

        // 显示结果
        function showResult(data) {
            const resultEl = document.getElementById('result');
            if (typeof data === 'string') {
                resultEl.textContent = data;
            } else {
                resultEl.textContent = JSON.stringify(data, null, 2);
            }
        }

        // 显示视频结果
        function showVideoResult(videoUrl) {
            const videoResultEl = document.getElementById('videoResult');
            videoResultEl.innerHTML = `
                <h4>🎬 生成的视频：</h4>
                <video controls width="600">
                    <source src="${videoUrl}" type="video/mp4">
                    您的浏览器不支持视频播放。
                </video>
                <p><a href="${videoUrl}" target="_blank">🔗 在新窗口中打开</a></p>
            `;
            videoResultEl.style.display = 'block';
        }

        // 设置加载状态
        function setLoading(loading) {
            const btn = document.getElementById('generateBtn');
            if (loading) {
                btn.innerHTML = '<span class="loading"></span>生成中...';
                btn.disabled = true;
            } else {
                btn.innerHTML = '🚀 生成视频';
                btn.disabled = false;
            }
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 页面加载完成后测试服务连接
        window.addEventListener('load', async function() {
            try {
                const response = await fetch(`${BASE_URL}/api/video/health`);
                const data = await response.json();
                if (data.status === 'UP') {
                    showStatus('服务连接正常，请上传图片开始生成视频', 'success');
                }
            } catch (error) {
                showStatus('服务连接失败，请检查后端服务是否启动', 'error');
            }
        });
    </script>
</body>
</html>